const express  = require ('express');
const pool = require('../pool');
const router = express.Router();


router.get('/queryAll',(req,res,next)=>{
    let page = (req.query.page -1)*18
    let pageCount = 18
    pool.query(`select * from westDraw limit ${page},${pageCount}`,(err,r)=>{
        if(err){
            return next(err)
        }
        pool.query('select count(*) from westDraw',(err,resp)=>{
            if(err){
                return next(err)
            }
            let pageSize = Math.ceil(resp[0]['count(*)']/pageCount);
            if(r.length !=0){
                res.send({code:200,data:{data:r,pageSize}})
            }
        })
    })
})

router.post('/add',(req,res,next)=>{
    let src = req.body.imgSrc;
    let uname = req.body.uname; //作者名
    let name = req.body.name //画名

    pool.query('insert into westDraw values(null,?,?,?,default,default)',[src,uname,name],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'添加成功'})
    })
})

router.post('/delete',(req,res,next)=>{
    let id = req.body.w_id;
    console.log(id)
    pool.query(`delete from westDraw where w_id=${id}`,(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除成功'})
    })
})

router.post('/update',(req,res,next)=>{
    let id = req.body.id;
    let uname = req.body.uname; //作者名
    let name = req.body.name //画名
    pool.query(`update westDraw set username=?,dname=? where w_id=${id}`,[uname,name],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'修改成功'})
    })
})
//查询所有浏览量
router.get("/queryLook",async (req,res,next)=>{
    let sql="select sum(look) as sumlw from westDraw"
    pool.query(sql,(err,r)=>{
       if(err){
        return next(err)
       }
       res.send({code:200,data:r})
    })
})
//查询所有下载量
router.get("/queryDown",async (req,res,next)=>{
    let sql="select sum(down) as sumdw from westDraw"
    pool.query(sql,(err,r)=>{
       if(err){
        return next(err)
       }
       res.send({code:200,data:r})
    })
})
module.exports = router;